/**
 * 动画垂直滚动到页面指定位置
 * @param { Number } currentY 当前位置
 * @param { Number } targetY 目标位置
 */
export function scrollAnimation(currentY, targetY) {
	// 获取当前位置方法
	// const currentY = document.documentElement.scrollTop || document.body.scrollTop

	// 计算需要移动的距离
	let needScrollTop = targetY - currentY;
	let _currentY = currentY;
	setTimeout(() => {
		// 一次调用滑动帧数，每次调用会不一样
		const dist = Math.ceil(needScrollTop / 10);
		_currentY += dist;
		window.scrollTo(_currentY, currentY);
		// 如果移动幅度小于十个像素，直接移动，否则递归调用，实现动画效果
		if (needScrollTop > 10 || needScrollTop < -10) {
			scrollAnimation(_currentY, targetY);
		} else {
			window.scrollTo(_currentY, targetY);
		}
	}, 1);
}
export default {
	inserted(el, binding) {
		const { self = false } = binding.modifiers || {};
		const value = binding.value;
		const options = (typeof value === "object" && value.options) || { passive: true };
		const handler =
			typeof value === "function" || "handleEvent" in value ? value : value.handler;

		const target = self ? el : binding.arg ? document.querySelector(binding.arg) : window;

		if (!target) return;

		target.addEventListener("scroll", handler, options);

		el._onScroll = {
			handler,
			options,
			// Don't reference self
			target: self ? undefined : target
		};
	},
	unbind(el) {
		if (!el._onScroll) return;

		const { handler, options, target = el } = el._onScroll;

		target.removeEventListener("scroll", handler, options);
		delete el._onScroll;
	}
};
